using Microsoft.EntityFrameworkCore;
using MediPlatform.Infeartructure;
using MediPlatform.Read.Api.Models;
using MediPlatform.Domain.Order;

namespace MediPlatform.Read.Api.Services
{
    public class ConsultationOrderService
    {
        private readonly MyDbContext _context;
        private readonly ILogger<ConsultationOrderService> _logger;

        public ConsultationOrderService(MyDbContext context, ILogger<ConsultationOrderService> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<ConsultationOrderPagedResponse> GetPagedListAsync(ConsultationOrderQueryRequest request)
        {
            try
            {
                _logger.LogInformation("开始查询问诊单分页列表，页码：{PageIndex}，页大小：{PageSize}", request.PageIndex, request.PageSize);

                var query = _context.ConsultationOrder
                    .Include(co => co.Patient)
                    .Include(co => co.Doctor)
                    .AsQueryable();

                // 根据患者姓名或手机号筛选
                if (!string.IsNullOrWhiteSpace(request.PatientNameOrPhone))
                {
                    query = query.Where(co => 
                        (co.Patient != null && co.Patient.Username != null && co.Patient.Username.Contains(request.PatientNameOrPhone)) ||
                        (co.Patient != null && co.Patient.PhoneNumber != null && co.Patient.PhoneNumber.Contains(request.PatientNameOrPhone))
                    );
                }

                // 根据时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(co => co.SubmitTime >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    var endTime = request.EndTime.Value.AddDays(1).AddSeconds(-1);
                    query = query.Where(co => co.SubmitTime <= endTime);
                }

                // 根据状态筛选
                if (request.Status.HasValue)
                {
                    query = query.Where(co => co.Status == request.Status.Value);
                }

                // 根据问诊方式筛选
                if (request.ConsultationType.HasValue)
                {
                    query = query.Where(co => co.ConsultationType == request.ConsultationType.Value);
                }

                // 根据问诊来源筛选（这里假设来源和类型相同，实际可能需要单独字段）
                if (request.Source.HasValue)
                {
                    query = query.Where(co => co.ConsultationType == request.Source.Value);
                }

                var totalCount = await query.CountAsync();

                var items = await query
                    .OrderByDescending(co => co.SubmitTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(co => new ConsultationOrderListItem
                    {
                        Id = co.Id,
                        OrderNo = co.OrderNo,
                        SubmitTime = co.SubmitTime,
                        PatientName = co.Patient != null ? co.Patient.Username : null,
                        PatientPhone = co.Patient != null ? co.Patient.PhoneNumber : null,
                        DepartmentName = GetDepartmentName(co.DepartmentId),
                        DoctorName = co.Doctor != null ? co.Doctor.Username : null,
                        ConsultationTypeText = GetConsultationTypeText(co.ConsultationType),
                        SourceText = GetSourceText(co.ConsultationType),
                        Fee = co.Fee,
                        Status = co.Status,
                        StatusText = GetStatusText(co.Status),
                        CreatedAt = co.CreatedAt
                    })
                    .ToListAsync();

                var result = new ConsultationOrderPagedResponse
                {
                    Items = items,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling((double)totalCount / request.PageSize),
                    CurrentPage = request.PageIndex,
                    PageSize = request.PageSize
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取问诊单分页列表失败");
                throw;
            }
        }

        public async Task<ConsultationOrderDetailResponse?> GetDetailAsync(long id)
        {
            try
            {
                _logger.LogInformation("开始查询问诊单详情，问诊单ID：{OrderId}", id);

                var order = await _context.ConsultationOrder
                    .Include(co => co.Patient)
                    .Include(co => co.Doctor)
                    .FirstOrDefaultAsync(co => co.Id == id);

                if (order == null)
                {
                    _logger.LogWarning("未找到问诊单，问诊单ID：{OrderId}", id);
                    return null;
                }

                // 获取问诊记录
                var record = await _context.ConsultationRecord
                    .FirstOrDefaultAsync(cr => cr.OrderId == id);

                // 获取问诊评价
                var review = await _context.ConsultationReview
                    .FirstOrDefaultAsync(cr => cr.OrderId == id);

                var result = new ConsultationOrderDetailResponse
                {
                    OrderInfo = new ConsultationOrderInfo
                    {
                        Id = order.Id,
                        OrderNo = order.OrderNo,
                        PatientId = order.PatientId,
                        PatientName = order.Patient?.Username,
                        PatientPhone = order.Patient?.PhoneNumber,
                        DoctorId = order.DoctorId,
                        DoctorName = order.Doctor?.Username,
                        HospitalId = order.HospitalId,
                        HospitalName = GetHospitalName(order.HospitalId),
                        DepartmentId = order.DepartmentId,
                        DepartmentName = GetDepartmentName(order.DepartmentId),
                        ConsultationType = order.ConsultationType,
                        ConsultationTypeText = GetConsultationTypeText(order.ConsultationType),
                        Status = order.Status,
                        StatusText = GetStatusText(order.Status),
                        AppointmentTime = order.AppointmentTime,
                        SubmitTime = order.SubmitTime,
                        Fee = order.Fee,
                        DiscountAmount = order.DiscountAmount,
                        ActualPayment = order.ActualPayment,
                        PaymentMethod = order.PaymentMethod,
                        PaymentTime = order.PaymentTime,
                        RefundAmount = order.RefundAmount,
                        RefundTime = order.RefundTime,
                        CancelReason = order.CancelReason,
                        CreatedAt = order.CreatedAt,
                        UpdatedAt = order.UpdatedAt
                    }
                };

                if (record != null)
                {
                    result.RecordInfo = new ConsultationRecordInfo
                    {
                        Id = record.Id,
                        OrderId = record.OrderId,
                        Symptoms = record.Symptoms,
                        MedicalHistory = record.MedicalHistory,
                        Diagnosis = record.Diagnosis,
                        TreatmentAdvice = record.TreatmentAdvice,
                        PrescriptionId = record.PrescriptionId,
                        Duration = record.Duration,
                        DurationText = GetDurationText(record.Duration),
                        CreatedAt = record.CreatedAt
                    };
                }

                if (review != null)
                {
                    result.ReviewInfo = new ConsultationReviewInfo
                    {
                        Id = review.Id,
                        OrderId = review.OrderId,
                        PatientId = review.PatientId,
                        PatientName = order.Patient?.Username,
                        DoctorId = review.DoctorId,
                        DoctorName = order.Doctor?.Username,
                        Rating = review.Rating,
                        RatingText = GetRatingText(review.Rating),
                        Comment = review.Comment,
                        CreatedAt = review.CreatedAt
                    };
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取问诊单详情失败，问诊单ID：{OrderId}", id);
                throw;
            }
        }

        public async Task<ConsultationOrderStatisticsResponse> GetStatisticsAsync()
        {
            try
            {
                _logger.LogInformation("开始获取问诊单统计数据");

                var totalCount = await _context.ConsultationOrder.CountAsync();
                var pendingPaymentCount = await _context.ConsultationOrder.CountAsync(co => co.Status == 0);
                var inProgressCount = await _context.ConsultationOrder.CountAsync(co => co.Status == 1);
                var completedCount = await _context.ConsultationOrder.CountAsync(co => co.Status == 2);
                var cancelledCount = await _context.ConsultationOrder.CountAsync(co => co.Status == 3);
                var refundedCount = await _context.ConsultationOrder.CountAsync(co => co.Status == 4);

                var result = new ConsultationOrderStatisticsResponse
                {
                    TotalCount = totalCount,
                    PendingPaymentCount = pendingPaymentCount,
                    InProgressCount = inProgressCount,
                    CompletedCount = completedCount,
                    CancelledCount = cancelledCount,
                    RefundedCount = refundedCount
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取问诊单统计数据失败");
                throw;
            }
        }

        private static string GetStatusText(int? status)
        {
            return status switch
            {
                0 => "待支付",
                1 => "进行中",
                2 => "已完成",
                3 => "已取消",
                4 => "已退诊",
                _ => "未知状态"
            };
        }

        private static string GetConsultationTypeText(int? consultationType)
        {
            return consultationType switch
            {
                1 => "视频问诊",
                2 => "电话问诊",
                3 => "图文问诊",
                4 => "极速电话",
                5 => "复诊开药",
                _ => "未知类型"
            };
        }

        private static string GetSourceText(int? source)
        {
            return source switch
            {
                1 => "视频问诊",
                2 => "电话问诊",
                3 => "图文问诊",
                4 => "极速图文",
                5 => "极速电话",
                _ => "未知来源"
            };
        }

        private static string GetDurationText(int? duration)
        {
            if (!duration.HasValue) return "0分钟";
            
            var minutes = duration.Value / 60;
            var seconds = duration.Value % 60;
            
            if (minutes > 0)
            {
                return seconds > 0 ? $"{minutes}分{seconds}秒" : $"{minutes}分钟";
            }
            
            return $"{seconds}秒";
        }

        private static string GetRatingText(int? rating)
        {
            if (!rating.HasValue) return "未评分";
            
            return rating.Value switch
            {
                1 => "1星",
                2 => "2星",
                3 => "3星",
                4 => "4星",
                5 => "5星",
                _ => "未知评分"
            };
        }

        private static string GetDepartmentName(long? departmentId)
        {
            return departmentId switch
            {
                1 => "内科",
                2 => "外科",
                3 => "儿科",
                4 => "妇科",
                5 => "呼吸科",
                6 => "骨科",
                7 => "神经科",
                8 => "皮肤科",
                9 => "心内科",
                10 => "消化科",
                _ => "未知科室"
            };
        }

        private static string GetHospitalName(long? hospitalId)
        {
            return hospitalId switch
            {
                1 => "北京协和医院",
                2 => "北京大学第一医院",
                3 => "上海交通大学医学院附属瑞金医院",
                4 => "复旦大学附属华山医院",
                5 => "中山大学附属第一医院",
                _ => "未知医院"
            };
        }
    }
} 